//
//  CourseDetailController.m
//  easystudy
//
//  Created by kane on 15/6/12.
//  Copyright (c) 2015年 kane. All rights reserved.
//

#import "CourseDetailController.h"
#import "TeamListController.h"
#import "DoctorTimeController.h"
#import "MapViewController.h"

@interface CourseDetailController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    __weak IBOutlet UIButton *favoriteBtn;
    
    __weak IBOutlet UIScrollView *contentScroll;
    __weak IBOutlet UIImageView *topIV;
    __weak IBOutlet UIView *topView;
    __weak IBOutlet UILabel *nameLbl;
    __weak IBOutlet UILabel *descLbl;
    __weak IBOutlet UIButton *descBtn;
    
    __weak IBOutlet UITableView *dataTable;
    
    __weak IBOutlet UIView *firstView;
    __weak IBOutlet UIImageView *avatarIV;
    __weak IBOutlet UILabel *doctorNameLbl;
    __weak IBOutlet UILabel *doctorPostionLbl;
    __weak IBOutlet UILabel *doctorScopeLbl;
    __weak IBOutlet UILabel *doctorDescLbl;
    
    __weak IBOutlet UIView *secondView;
    __weak IBOutlet UILabel *addressLbl;
    
    __weak IBOutlet UIView *thirdView;
    __weak IBOutlet UILabel *worktimeLbl;
    
    __weak IBOutlet UIView *coverView;
    
    NSMutableArray *doctorList;
    NSMutableArray *collectList;
}

@end

@implementation CourseDetailController
@synthesize dataInfo,hospitalID;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    doctorList = [NSMutableArray array];
    collectList = [NSMutableArray array];
    [self reloadHospitalInfo];
    [self reloadDoctorList];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initUI
{
    [descBtn drawCornerRadius:3];
    [avatarIV drawCornerRadius:5];
    NSString *url = dataInfo[@"logo"] && [dataInfo[@"logo"] isKindOfClass:[NSString class]] ? dataInfo[@"logo"]  : @"";
    [topIV setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",FileURL,url]] placeholderImage:[UIImage imageNamed:@"home_placeholder"]];

    nameLbl.text = dataInfo[@"name"];
    descLbl.text = dataInfo[@"brief"];
    addressLbl.text = dataInfo[@"address"];
    worktimeLbl.text = dataInfo[@"worktime"];

    [descLbl sizeToFit];
    [self reloadTopViewByHidden:NO];
}

- (void)reloadTopViewByHidden:(BOOL)hidden
{
    if (hidden) {
        topView.frame = (CGRect){topView.origin,topView.width,248};
    }else{
        CGFloat distance = descLbl.height - 20;
        topView.frame = (CGRect){topView.origin,topView.width,248 + distance};
    }
    descLbl.hidden = hidden;
    descBtn.frame = (CGRect){descBtn.minX,topView.height - descBtn.height - 15,descBtn.size};
    dataTable.frame = (CGRect){dataTable.minX,topView.maxY,dataTable.size};
    contentScroll.contentSize = CGSizeMake(fWidth_Current, dataTable.maxY);
}

- (void)reloadHospitalInfo
{
    NSDictionary *param = @{@"type":@"1",@"srcId":self.hospitalID};
    [WebService findFavoriteList:param WithBlock:^(id result, NSError *error) {
        if (!error) {
            [collectList removeAllObjects];
            [collectList addObjectsFromArray:result[@"data"][@"collectlist"]];
            favoriteBtn.selected = collectList.count > 0;
        }
    }];
}

- (void)reloadDoctorList
{
    NSDictionary *params = @{@"cid":self.hospitalID};
    [WebService findDoctorList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            [doctorList removeAllObjects];
            [doctorList addObjectsFromArray:result[@"docList"]];
            if (doctorList.count > 0) {
                NSDictionary *item = doctorList.firstObject;
                NSString *url = item[@"avatar"] && [item[@"avatar"] isKindOfClass:[NSString class]] ? item[@"avatar"]  : @"";;
                [avatarIV setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"defaultDoctor"]];
                doctorNameLbl.text = [item[@"name"] isKindOfClass:[NSString class]]? item[@"name"]:@"";
                doctorPostionLbl.text = item[@"position"];
                doctorScopeLbl.text = item[@"goodat"];
                doctorDescLbl.text = [item[@"brief"] isKindOfClass:[NSString class]]? item[@"brief"]:@"";
            }else{
                doctorNameLbl.text = @"医生";
                doctorDescLbl.text = @"暂无资料";
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败,请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
}

#pragma mark - User Actions

- (IBAction)backBtnPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)favoriteBtnPressed:(UIButton *)sender {
    if (![UserEntity sharedUser].loginSuccess) {
        [self.view makeToast:@"请先登录~"];
        return;
    }
    sender.selected = !sender.selected;
    if (sender.selected) {
        NSDictionary *params = @{@"srcId":self.hospitalID,@"type":@"1"};
        [WebService saveFavorite:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"data"][@"code"] boolValue]) {
                    [self.view makeToast:@"收藏成功"];
                }else{
                    [self.view makeToast:@"收藏失败"];
                    sender.selected = !sender.selected;
                }
            }
        }];
    }else{
        for (NSDictionary *dic in collectList) {
            NSDictionary *params = @{@"cltid":dic[@"cltid"]};
            [WebService deleteFavorite:params WithBlock:^(id result, NSError *error) {
                if (!error) {
                    if ([result[@"data"][@"code"] boolValue]) {
                        [self.view makeToast:@"删除成功"];
                    }else{
                        [self.view makeToast:@"删除失败"];
                        sender.selected = !sender.selected;
                    }
                }
            }];
        }
    }
}

- (IBAction)shareBtnPressed:(id)sender
{
    coverView.hidden = NO;
    
}

- (IBAction)coverBtnPressed:(id)sender
{
    coverView.hidden = YES;
}


- (IBAction)descBtnPressed:(id)sender {
    descBtn.selected = !descBtn.selected;
    [self reloadTopViewByHidden:descBtn.selected];
}

- (IBAction)callBtnPressed:(id)sender
{
    NSString *phone = [dataInfo[@"phone"] isKindOfClass:[NSString class]] ? dataInfo[@"phone"]:@"";
    NSString *msg = [NSString stringWithFormat:@"我们将拨打%@为您预约",phone];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"telprompt://"]]) {
            NSString *phone = [dataInfo[@"phone"] isKindOfClass:[NSString class]] ? dataInfo[@"phone"]:@"";
            if (phone.length > 0) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[@"telprompt://" stringByAppendingString:phone]]];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"本设备不支持拨打电话" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}

#pragma mark - User Actions

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    switch (indexPath.row) {
        case 0:
            height = 85;
            break;
        case 1:
        case 2:
            height = 44;
            break;
    }
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"DetailCell";
    UITableViewCell *cell = cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    switch (indexPath.row) {
        case 0:{
            [cell.contentView addSubview:firstView];
        } break;
        case 1:{
            [cell.contentView addSubview:secondView];
        } break;
        case 2:{
            [cell.contentView addSubview:thirdView];
        } break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            TeamListController *teamVC = [[TeamListController alloc] init];
            teamVC.doctorList = doctorList;
            teamVC.cid = self.hospitalID;
            teamVC.hospitalName = nameLbl.text;
            [self.navigationController pushViewController:teamVC animated:YES];
        } break;
        case 1:{
            //跳转到地图
            MapViewController *mapVC = [[MapViewController alloc] init];
            mapVC.targetLatitude = dataInfo[@"latitude"];
            mapVC.targetLongitude = dataInfo[@"longitude"];
            mapVC.targetAddress = dataInfo[@"address"];
            mapVC.isForTargetLocation = YES;
            [self.navigationController pushViewController:mapVC animated:YES];
            
        } break;
        case 2:{
            DoctorTimeController *timeVC = [[DoctorTimeController alloc] init];
            [self.navigationController pushViewController:timeVC animated:YES];
        } break;
    }
}
@end
